package ru.agiledev.akb.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import ru.agiledev.akb.client.ValidationService;
import ru.agiledev.akb.server.domain.presentation.Author;
import ru.agiledev.akb.server.hibernate.HibernateUtil;
import ru.agiledev.akb.shared.exception.ValidationException;

import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by a.kirillov
 * Date: 4/4/11 Time: 11:17 PM
 */
public class ValidationServiceImpl extends RemoteServiceServlet implements ValidationService

{
    @Override
    public boolean validateLogin(String login) throws ValidationException {
        if(login.length() < 5) return false;

        boolean regexp = Pattern.matches("\\b[A-Za-z0-9]+\\b", login);
        if(regexp){
            Session session = HibernateUtil.getSessionFactory().openSession();
            List<Author> list = session.createCriteria(Author.class).add(Restrictions.eq("login", login)).list();

            if(list.size()>0){
                session.close();
                throw new ValidationException("Данный логин уже занят.");
            }


        }


        return regexp;
    }

    @Override
    public boolean validateEmail(String email) throws ValidationException {
        boolean regexp = Pattern.matches("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b", email);

        if(regexp){
            Session session = HibernateUtil.getSessionFactory().openSession();
            List<Author> list = session.createCriteria(Author.class).add(Restrictions.eq("email", email)).list();

            if(list.size()>0){
                session.close();
                throw new ValidationException("Данный адрес зарегистрирован другим пользователем.");
            }


        }

        return regexp;
    }

    @Override
    public String validatePassword(String password) {
        return "";  //To change body of implemented methods use File | Settings | File Templates.
    }
}
